package com.lego.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lego.bean.Goods;
import com.lego.bean.OrderDTO;
import com.lego.bean.Orders;
import com.lego.bean.OrdersAndGoodsImgVO;
import com.lego.dao.BaseDao;
import com.lego.dao.OrdersDao;

public class OrdersDaoImpl implements OrdersDao {

	@Override
	public int selectSellerSold(int sellerId) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		String sql = "SELECT count(1) as totalRows FROM orders WHERE (orderStatus = 'delivered' || orderStatus = 'finished' || orderStatus = 'toBeReviewed') AND sellerId = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setObject(1, sellerId);
			System.out.println(ps);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("totalRows");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		return rows;
	}

	@Override
	public int selectTotalSold(int goodsId) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		String sql = "SELECT count(1) as totalRows FROM orders WHERE (orderStatus = 'delivered' || orderStatus = 'finished' || orderStatus = 'toBeReviewed') AND goodsId = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setObject(1, goodsId);
			System.out.println(ps);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("totalRows");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		return rows;
	}

	@Override
	public int addOrders(Orders order) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		System.out.println("dao+"+order);
		String sql = "INSERT INTO orders(orderNumber,sellerId,userId,goodsId,totalQuantity,totalAmount,orderTime,orderStatus) VALUES "
				+ "(?,?,?,?,?,?,now(),?)";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setString(1, order.getOrderNumber());
			ps.setInt(2, order.getSellerId());
			ps.setInt(3, order.getUserId());
			ps.setInt(4, order.getGoodsId());
			ps.setInt(5, order.getTotalQuantity());
			ps.setDouble(6, order.getTotalAmount());
			ps.setString(7,order.getOrderStatus());
			System.out.println(ps);
			ps.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}

	@Override
	public int updateStatus(String orderStatus, String orderNumber,String receivingAddress) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		List<Object> params = new ArrayList();
		String sql = "UPDATE orders SET orderStatus = ? ";
		params.add(orderStatus);
		if(receivingAddress!=null&&!receivingAddress.equals("")) {
			sql+=", receivingAddress = ? ";
			params.add(receivingAddress);
		}
		if(orderStatus=="toBeReviewed") {
			sql+=",deliveryTime=now() ";
		}
		sql+="WHERE orderNumber = ?";
		params.add(orderNumber);
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i+1, params.get(i));
			}
			System.out.println(ps);
			result = ps.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}

	@Override
	public List<OrderDTO> selectUserOrders(String orderStatus, int userId, int pageNum, int pageSize) {
	    Connection con = null;
	    PreparedStatement ps = null;
	    ResultSet res = null;
	    int result = 0;
		List<Object> params = new ArrayList();
	    List<OrderDTO> list = new ArrayList<>();
	    
	    String sql = "SELECT o.*, u.userName, g.goodsName FROM orders o " +
	                 "JOIN user u ON o.userId = u.userId " +
	                 "JOIN goods g ON o.goodsId = g.goodsId " +
	                 "WHERE 1=1 ";
	    
	    if(orderStatus!=null&&!("").equals(orderStatus)) {
	        sql+="AND o.orderStatus = ? ";
	        params.add(orderStatus);
	    }
	    if(userId!=0&&!("").equals(userId)) {
	        sql+="AND o.userId = ? ";
	        params.add(userId);
	    }
	    sql+="LIMIT ?,?";
	    int newPageNum = (pageNum-1)*pageSize;
	    params.add(newPageNum);
	    params.add(pageSize);

	    try {
	        con = BaseDao.getCon();
	        ps = con.prepareStatement(sql);
	        for (int i = 0; i < params.size(); i++) {
	            ps.setObject(i+1, params.get(i));
	        }
	        res = ps.executeQuery();
	        while(res.next()) {
	            OrderDTO dto = new OrderDTO();
	            
	            dto.setOrderId(res.getInt("orderId"));
	            dto.setOrderNumber(res.getString("orderNumber"));
	            dto.setSellerId(res.getInt("sellerId"));
		        dto.setUserId(res.getInt("userId"));
		        dto.setGoodsId(res.getInt("goodsId"));
		        dto.setTotalQuantity(res.getInt("totalQuantity"));
		        dto.setTotalAmount(res.getDouble("totalAmount"));
		        dto.setOrderTime(res.getDate("orderTime"));
		        dto.setReceivingAddress(res.getString("receivingAddress"));
		        dto.setDeliveryTime(res.getDate("deliveryTime"));
		        dto.setOrderStatus(res.getString("orderStatus"));
	            dto.setUserName(res.getString("userName"));
	            dto.setGoodsName(res.getString("goodsName"));
	            
	            list.add(dto);
	        }
	    } catch (SQLException e) {
	        e.printStackTrace();
	    } finally {
	        BaseDao.closeAll(con, ps, res);
	    }
	    return list;
	}

	@Override
	public int selectUserRows(String orderStatus, int userId) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		List<Object> params = new ArrayList();
		String sql = "SELECT count(*) as totalRows FROM orders WHERE 1=1 ";
		if(orderStatus!=null&&!("").equals(orderStatus)) {
			sql+="AND orderStatus = ? ";
			params.add(orderStatus);
		}
		if(userId!=0&&!("").equals(userId)) {
			sql+="AND userId = ? ";
			params.add(userId);
		}
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i+1, params.get(i));
			}
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("totalRows");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		return rows;
	}

	@Override
	public List<OrdersAndGoodsImgVO> selectPersonalReview(int userId,int pageNum,int pageSize) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<OrdersAndGoodsImgVO> list = new ArrayList();
		List<Object> params = new ArrayList();
		String sql = "SELECT * FROM orders AS o JOIN goods AS g JOIN reviews AS r WHERE o.orderId = r.orderId AND r.userId = o.userId AND g.goodsId = o.goodsId ";
		if(userId!=0&&!("").equals(userId)) {
			sql+="AND o.userId = ? ";
			params.add(userId);
		}
		sql+="LIMIT ?,?";
		int newPageNum = (pageNum-1)*pageSize;
		params.add(newPageNum);
		params.add(pageSize);
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i+1, params.get(i));
			}
			System.out.println(ps);
			res = ps.executeQuery();
			while(res.next()) {
				OrdersAndGoodsImgVO order = new OrdersAndGoodsImgVO();
		        order.setOrderId(res.getInt("orderId"));
		        order.setOrderNumber(res.getString("orderNumber"));
		        order.setSellerId(res.getInt("sellerId"));
		        order.setUserId(res.getInt("userId"));
		        order.setGoodsId(res.getInt("goodsId"));
		        order.setTotalQuantity(res.getInt("totalQuantity"));
		        order.setTotalAmount(res.getDouble("totalAmount"));
		        order.setOrderTime(res.getDate("orderTime"));
		        order.setReceivingAddress(res.getString("receivingAddress"));
		        order.setDeliveryTime(res.getDate("deliveryTime"));
		        order.setOrderStatus(res.getString("orderStatus"));
		        order.setGoodsImg(res.getString("goodsImg"));
		        order.setReviewId(res.getInt("reviewId"));
		        order.setReviewContext(res.getString("rewContext"));
		        list.add(order);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		return list;
	}

	@Override
	public int seletPersonalRws(int userId) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		List<Object> params = new ArrayList();
		String sql = "SELECT count(*) as totalRows FROM orders AS o JOIN goods AS g JOIN reviews AS r WHERE o.orderId = r.orderId AND r.userId = o.userId AND g.goodsId = o.goodsId ";
		if(userId!=0&&!("").equals(userId)) {
			sql+="AND o.userId = ? ";
			params.add(userId);
		}
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.size(); i++) {
				ps.setObject(i+1, params.get(i));
			}
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("totalRows");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		return rows;
	}
	
	@Override
	public int selectGoodsId(int orderId) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int result = 0;
		String sql = "SELECT goodsId FROM orders where orderId = ?";
		con = BaseDao.getCon();
		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, orderId);
			res = ps.executeQuery();
			if(res.next()) {
				result = res.getInt("goodsId");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public int changeStatus(int orderId) {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int result = 0;
		String sql = "UPDATE orders SET orderstatus = 'finished'\r\n" + 
				"WHERE orderId = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, orderId);
			result = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public int changeStatusById(String orderStatus, int orderId) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "UPDATE orders SET orderStatus = ? where orderId = ? ";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setString(1, orderStatus);
			ps.setInt(2, orderId);
			System.out.println(ps);
			result = ps.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}
	@Override
	public int changeStatusTime(String orderStatus, int orderId) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "UPDATE orders SET orderStatus = ? , deliveryTime = now() where orderId = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setString(1, orderStatus);
			ps.setInt(2, orderId);
			System.out.println(ps);
			result = ps.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}
	
	@Override
	public OrderDTO selectOrderByONum(String orderNum) {
	    Connection con = null;
	    PreparedStatement ps = null;
	    ResultSet rs = null;
	    OrderDTO orderDTO = null;
	    String sql = "SELECT "
	    		+ "  o.*,g.goodsName,u.userName,o.totalAmount,o.orderTime,o.deliveryTime,o.orderStatus "
	    		+ "FROM "
	    		+ "  `user` AS u "
	    		+ "  JOIN goods AS g "
	    		+ "  JOIN orders AS o "
	    		+ "  WHERE u.userId=o.userId "
	    		+ "  AND o.goodsId=g.goodsId "
	    		+ " AND orderNumber=?";
	    
	    try {
	        con = BaseDao.getCon();
	        ps = con.prepareStatement(sql);
	        ps.setString(1, orderNum);
	        System.out.println(ps);
	        rs = ps.executeQuery();
	        
	        if (rs.next()) {
	            orderDTO = new OrderDTO();
	            orderDTO.setGoodsName(rs.getString("goodsName"));
	            orderDTO.setUserName(rs.getString("userName"));
	            orderDTO.setOrderId(rs.getInt("orderId"));
	            orderDTO.setOrderNumber(rs.getString("orderNumber"));
	            orderDTO.setUserId(rs.getInt("userId"));
	            orderDTO.setGoodsId(rs.getInt("goodsId"));
	            orderDTO.setTotalQuantity(rs.getInt("totalQuantity"));
	            orderDTO.setTotalAmount(rs.getDouble("totalAmount"));
	            orderDTO.setOrderTime(rs.getDate("orderTime"));
	            orderDTO.setReceivingAddress(rs.getString("receivingAddress"));
	            orderDTO.setDeliveryTime(rs.getDate("deliveryTime"));
	            orderDTO.setOrderStatus(rs.getString("orderStatus"));
	        }
	    } catch (SQLException e) {            
	        e.printStackTrace();
	    } finally {
	        BaseDao.closeAll(con, ps, rs);
	    }
	    return orderDTO;
	}
	
	@Override
	public int selectTodayOrders() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int result = 0;
		String sql = "SELECT count(*) AS total from orders where orderTime = CURDATE()";
		con = BaseDao.getCon();
		try {
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				result = res.getInt("total");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
	        BaseDao.closeAll(con, ps, null);
	    }
		return result;
	}
	
	@Override
	public double selectTodayAmount() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		double result = 0;
		String sql = "SELECT sum(totalAmount) as total from orders where orderTime = CURDATE() WHERE orderStatus != 'pending'";
		con = BaseDao.getCon();
		try {
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				result = res.getInt("total");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
	        BaseDao.closeAll(con, ps, null);
	    }
		return result;
	}

	@Override
	public double selectAllAmount() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		double result = 0;
		String sql = "SELECT sum(totalAmount) as total from orders WHERE orderStatus != 'pending'";
		con = BaseDao.getCon();
		try {
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				result = res.getInt("total");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
	        BaseDao.closeAll(con, ps, null);
	    }
		return result;
	}

	@Override
	public double[] selectEveryCard() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		double[] data = new double[10]; 
		String sql = "SELECT g.goodsType, COUNT(o.orderId) AS total FROM goods AS g LEFT JOIN orders AS o " + 
				"ON o.goodsId = g.goodsId GROUP BY g.goodsType";
		con = BaseDao.getCon();
		int i = 0;
		try {
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			while(res.next()) {
				data[i] = res.getInt("total");
				i++;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
	        BaseDao.closeAll(con, ps, null);
	    }
		return data;
	}

}
